﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Interface.Api;

namespace yafc.TaskScheduler
{
	class Scheduler
	{
		#region Fields

		private Queue<Task> taskQueue = new Queue<Task>();
		private ManualResetEvent eventExit = new ManualResetEvent(false);
		private ManualResetEvent eventExited = new ManualResetEvent(false);

		#endregion

		#region Public Properties

		public ManualResetEvent Exited
		{
			get
				{ return eventExited; }
		}

		#endregion

		#region Public Methods

		public void add(Task T)
		{
			lock(taskQueue)
				{ taskQueue.Enqueue(T); }
		}

		public void exit()
		{
			eventExit.Set();
		}

		public void run()
		{
			while (true)
			{
				if (eventExit.WaitOne(0))
					break;

				process();
			}
			eventExited.Set();
		}

		#endregion

		#region Non-Public Methods

		private void process()
		{
			Task task;
			lock(taskQueue)
			{
				if (taskQueue.Count == 0)
				{
					Thread.Sleep(100);
					return;
				}
				task = taskQueue.Dequeue();
			}
			task.process();
		}

		#endregion
	}
}
